package edu.bw.advice;

import edu.bw.utils.TransactionManager;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Log4j2
@Aspect
public class TransactionAdvice {
    @Autowired
    private TransactionManager transactionManager;
    @Pointcut("execution(* edu.bw.service..*.*(..)) " +
            "&& ! execution(* edu.bw..*.find*(..))" )
    public void pointcut() {
    }
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        log.info("事务开始");
        transactionManager.beginTransaction();
        try {
            Object ret = pjp.proceed();
            log.info("事务提交");
            transactionManager.commit();
            return ret;
        } catch (Throwable e) {
            log.info("事务回滚");
            transactionManager.rollback();
            throw e;
        } finally {
            log.info("事务关闭");
            transactionManager.close();
        }
    }
}
